﻿using ReflectionStudio.Core.Events;
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace WPFExcelReport
{
    public partial class TUFWB13
    {
        public TUFWB13()
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;
            MV = new VICC_STOCK();
            this.DataContext = MV;
            InitializeComponent();
            LO = "01";
            LB = "ZZ";
            VAR = "0700";
            DESS = "0700";
            DTSTART = Helpers.Helper.GetPreviousday(-1);
            DTEND = MV.date;
            TMV.OnMessage += TMV_OnMessage;
            //ART = "201605300443";
        }

        private void TMV_OnMessage(object sender, MessageEventArgs e)
        {
            string msg = e.Info.Details;
            if (msg.Contains("转换完成"))
                IsBusy = false;
            if (msg.Contains("开始转换"))
                IsBusy = true;
            INFO = msg;
            
        }

        public override void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            base.bgWorker_RunWorkerCompleted(sender, e);
            vwMaster.View.MoveCurrentTo(-1);
            EventDispatcher.Instance.RaiseStatus("完成数据更新", StatusEventType.StopProgress);
        }
        public override void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            IsReset = false;
            base.Window_Loaded(sender, e);
        }
        public override void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            base.bgWorker_DoWork(sender, e);
            EventDispatcher.Instance.RaiseStatus("开始更新数据", StatusEventType.RunningProgress);
            TMV.EXEWI09(PM["DTSTART"], "F");
            TMV.EXEWI09(PM["DTEND"], "F");

        }
        public void FilterMaster_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string filter = "ART LIKE '%" + ART.Trim() + "%'";
                cvMaster.CustomFilter = filter;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex.Message);
            }

        }

        public void FilterMasterClear_Click(object sender, RoutedEventArgs e)
        {

            cvMaster.CustomFilter = null;
        }
        public override void NewCommand(object sender, RoutedEventArgs e)
        {
            PM["DTSTART"] = DTSTART;
            PM["DTEND"] = DTEND;
            bgWorker.RunWorkerAsync();
            Tracer.Info("", "已经更新完成");
            base.NewCommand(sender, e);
            IsReset = true;
        }

        public override void QueryCommand(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!IsReset)
                {
                    MessageBox.Show("请完成数据更新");
                    return;
                }
                IsReset = false; 
                NormalTask = Task.Factory.StartNew(() => LOADALL(), new CancellationTokenSource().Token, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
                base.QueryCommand(sender, e);

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex.Message);
            }
        }
        public override void LOADALL()
        {
            try
            {
                TMV.RaiseMessage("开始转换");
                TMV.CALL = 0;
                TMV.CNOW = 0;
                dwData = TMV.WBWI.TBMain.NewRow();
                dwData["WBEWMANDANT"] = app.Mandant;
                dwData["WBEWBUCHDAT"] = DTSTART;
                string filter = " AND WBEWBUCHDAT||SUBSTR('00000000'||TO_CHAR(WBEWBUCHUHR),-8)>='" + DTSTART + Helpers.Helper.Right("00000000" + VAR, 4) + "0000" + "' AND WBEWBUCHDAT||SUBSTR('00000000'||TO_CHAR(WBEWBUCHUHR),-8)<='" + DTEND + Helpers.Helper.Right("0000" + DESS, 4) + "0000'";
                if (ART.Trim().Length > 0)
                {
                    filter = " AND WBEWSTKNR='"+ART+"'" + filter;
                }
                dwData["WBEWFILLER"] = filter;
                string src, str1 = "", str2 = "", str3 = "";
                src = DTSTART;
                Helpers.Helper.GetSplitDate(ref str1, ref str2, ref str3, src);
                string date1 = str1;
                Helpers.Helper.GetSplitDate(ref str1, ref str2, ref str3, DTEND);
                TMV.RaiseMessage("读取数据");
                SResult = TMV.QSYHPROD2UFS(dwData);
                TMV.RaiseMessage("开始写入");
                int idx = 0;
                int count = SResult.Tables[0].Rows.Count;
                TMV.CALL = count;
                foreach (DataRow row in SResult.Tables[0].Rows)
                {
                    VAR = Helpers.Helper.Right("0000" + VAR, 4);
                    DESS = Helpers.Helper.Right("0000" + DESS, 4);
                    row["CINVNAME"] = Helpers.Helper.GetGB2312Value(row["CINVNAME"].ToString()).Trim();
                    row["CINVSTD"] = Helpers.Helper.GetGB2312Value(row["CINVSTD"].ToString()).Trim();
                    row["CREATEMAN"] = Helpers.Helper.GetGB2312Value(row["CREATEMAN"].ToString()).Trim();
                    row["PLOT"] = Helpers.Helper.GetGB2312Value(row["PLOT"].ToString()).Trim();
                    try
                    {
                        TMV.BATCHWB14(row);
                    }
                    catch (Exception ex)
                    {
                        TMV.RaiseMessage(idx + "/" + count + "转换遇到问题");
                        Helpers.LogHelper.error(ex.StackTrace + ex.Message);

                    }
                    idx++;
                    TMV.CNOW = idx;
                    TMV.RaiseMessage(Helpers.Helper.RoundX(100 * 1.0 * idx / count, 1) + "%正在转换");
                    
                }
                TMV.RESTPOST();
                TMV.RaiseMessage(count+ "转换完成");  
                MergeData(SResult, false);
            }
            catch (Exception ex)
            {
                Helpers.LogHelper.error(ex.StackTrace + ex.Message);
            }
        }
        public override void PrintCommand(object sender, RoutedEventArgs e)
        {
            DataSet Set = new DataSet();
            Set.Merge(TBMain);
            cDR.PRINT(Set);
            base.PrintCommand(sender, e);
        }
    }
    public partial class VICC_STOCK
    {
        SqlConnection _SqlServerDB;
        string conn = @"Data Source=192.168.1.88;Initial Catalog=SJFZ_zjk;Persist Security Info=True;User ID=zjk;Password=123456";
        public SqlConnection SqlServerDB
        {
            get
            {
                if (_SqlServerDB == null)
                    _SqlServerDB = new SqlConnection(conn);
                return _SqlServerDB;
            }
        }
        public void WRITEUFSDB(DataRow dwData)
        {
            try
            {
                /*
                17.Insert Into T_Student(F_Code, F_Name, F_Memo, F_Memo2) select
18.'code001', 'name001', 'memo001', '备注001' union all select
19.'code002', 'name002', 'memo002', '备注002' union all select
20.'code003', 'name003', 'memo003', '备注003' union all select
21.'code004', 'name004', 'memo004', '备注004' union all select
22.'code005', 'name005', 'memo005', '备注005' union all select
23.'code006', 'name006', 'memo006', '备注006'
*/
                SqlCommand SQLCmd;
                SQLCmd = SqlServerDB.CreateCommand(); 
                SQLCmd.CommandText = "INSERT INTO SJFZ_zjk.dbo.SJFZ_BarTable (WBEWBELEG,WBEWLFDNR,cinvcode,cinvname,cinvstd,barCode,plot,qty,ddate,machNo,volumenum,volume,userBZ,employid,createman,remark) "
                    + " VALUES (:WBEWBELEG:,:WBEWLFDNR:,:CINVCODE:,:CINVNAME:,:CINVSTD:,:BARCODE:,:PLOT:,:QTY:,:DDATE:,:MACHNO:,:VOLUMENUM:,:VOLUME:,:USERBZ:,:EMPLOYID:,:CREATEMAN:,:REMARK:)";
                SQLCmd.CommandText = INTEXDBC.InjectData(SQLCmd.CommandText, dwData);
                if (!app.IsSQLDEMO)
                {
                    INTEXDBC.Connect2Proxy(SQLCmd);

                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }

        public   void RESTPOST()
        {
            if (CommdandInsert.Length > 0)
            {
                BATCHPOST();
            }
        }
        public override string BATCHINSERT(DataRow dwData)
        {
            CommdandInsert += " SELECT :WBEWBELEG:,:WBEWLFDNR:,:CINVCODE:,:CINVNAME:,:CINVSTD:,:BARCODE:,:PLOT:,:QTY:,:DDATE:,:MACHNO:,:VOLUMENUM:,:VOLUME:,:USERBZ:,:EMPLOYID:,:CREATEMAN:,:REMARK: UNION ALL";
            CommdandInsert = INTEXDBC.InjectData(CommdandInsert, dwData); 
            return CommdandInsert;
        }

        public void BATCHPOST()
        {
            CommdandInsert = ("INSERT INTO SJFZ_zjk.dbo.SJFZ_BarTable (WBEWBELEG,WBEWLFDNR,cinvcode,cinvname,cinvstd,barCode,plot,qty,ddate,machNo,volumenum,volume,userBZ,employid,createman,remark) "
                + CommdandInsert + "****").Replace("UNION ALL****", "");
            SqlCommand SQLCmd;
            SQLCmd = SqlServerDB.CreateCommand();
            SQLCmd.CommandText = CommdandInsert;
            CommdandInsert = "";
            if (!app.IsSQLDEMO)
            {
                INTEXDBC.Connect2Proxy(SQLCmd);

            }
        }
        public override void BATCHWB14(DataRow _dwWB14)
        {
             BATCHINSERT(_dwWB14);
            if (CommdandInsert.Length > 8000)
            {
                BATCHPOST();
            }
        }
    }
}
